package com.ibm.iisp.common.sample;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import com.ibm.iisp.auth.service.InvocationSecurityMetadataSourceService;
import com.ibm.iisp.auth.service.UserDetailsServiceImpl;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Value("${security.salt:Sec@Iisp}")
	String salt;
	@Autowired
	InvocationSecurityMetadataSourceService metadataSourceService;

	@Bean
	@Override
	protected AuthenticationManager authenticationManager() throws Exception {
		return super.authenticationManager();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {

		// 允许所有用户访问"/"和"/home"
		http.authorizeRequests().antMatchers("/", "/index.html").permitAll()
				// 其他地址的访问均需验证权限
				.anyRequest().authenticated().and().httpBasic().and().logout().logoutSuccessUrl("/logout.html")// 退出登录后的默认url是"/home"
				.permitAll();
	}

	@Override
	public void init(final WebSecurity web) throws Exception {
		final HttpSecurity http = getHttp();
		web.addSecurityFilterChainBuilder(http).postBuildAction(new Runnable() {
			@Override
			public void run() {
				FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
				securityInterceptor.setSecurityMetadataSource(metadataSourceService);
				web.securityInterceptor(securityInterceptor);
			}
		});
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

		auth.userDetailsService(customUserDetailsService()).passwordEncoder(passwordEncoder());

	}

	/**
	 * 设置用户密码的加密方式
	 * 
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		Map<String, PasswordEncoder> encoders = new HashMap<>();
		String idForEncode = "bcrypt";
		encoders.put(idForEncode, new BCryptPasswordEncoder());
		//下面是为了兼容老的password算法
		@SuppressWarnings("deprecation")
		PasswordEncoder nencoder = org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance();
		encoders.put("noop", nencoder);
		@SuppressWarnings("deprecation")
		PasswordEncoder sencoder = new org.springframework.security.crypto.password.StandardPasswordEncoder(salt);
		encoders.put("sha256", sencoder);

		PasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(idForEncode, encoders);
		return passwordEncoder;
	}

	/**
	 * 自定义UserDetailsService，从数据库中读取用户信息
	 * 
	 * @return
	 */
	@Bean
	public UserDetailsService customUserDetailsService() {
		return new UserDetailsServiceImpl();
	}

}
